<template>
  <div class="admin-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>管理员管理</span>
          <el-button type="primary" @click="handleCreate">新增管理员</el-button>
        </div>
      </template>
      
      <el-table :data="admins" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 管理员表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form
        ref="adminFormRef"
        :model="adminForm"
        :rules="adminFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="adminForm.username" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="adminForm.nickname" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="adminForm.email" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="adminForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input v-model="adminForm.password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdmins, createAdmin, updateAdmin, deleteAdmin } from '@/api/admin'

// 管理员数据
const admins = ref([])
const loading = ref(false)

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单引用
const adminFormRef = ref()

// 管理员表单数据
const adminForm = reactive({
  id: 0,
  username: '',
  nickname: '',
  email: '',
  status: 1,
  password: ''
})

// 表单验证规则
const adminFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

// 获取管理员列表
const fetchAdmins = async () => {
  loading.value = true
  try {
    const res: any = await getAdmins({
      page: pagination.page,
      page_size: pagination.pageSize
    })
    
    if (res.success) {
      admins.value = res.data
      pagination.total = res.pagination.total
    } else {
      ElMessage.error(res.message || '获取管理员列表失败')
    }
  } catch (error) {
    ElMessage.error('获取管理员列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页面大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchAdmins()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  pagination.page = val
  fetchAdmins()
}

// 处理新增
const handleCreate = () => {
  dialogTitle.value = '新增管理员'
  isEdit.value = false
  // 重置表单
  Object.assign(adminForm, {
    id: 0,
    username: '',
    nickname: '',
    email: '',
    status: 1,
    password: ''
  })
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑管理员'
  isEdit.value = true
  // 填充表单数据
  Object.assign(adminForm, row)
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除管理员 "${row.username}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res: any = await deleteAdmin(row.id)
      if (res.success) {
        ElMessage.success('删除成功')
        fetchAdmins()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 提交表单
const submitForm = async () => {
  if (!adminFormRef.value) return
  
  await adminFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let res: any
        if (isEdit.value) {
          // 编辑
          res = await updateAdmin(adminForm.id, {
            username: adminForm.username,
            nickname: adminForm.nickname,
            email: adminForm.email,
            status: adminForm.status
          })
        } else {
          // 新增
          res = await createAdmin({
            username: adminForm.username,
            nickname: adminForm.nickname,
            email: adminForm.email,
            password: adminForm.password
          })
        }
        
        if (res.success) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          dialogVisible.value = false
          fetchAdmins()
        } else {
          ElMessage.error(res.message || (isEdit.value ? '更新失败' : '创建失败'))
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      }
    }
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAdmins()
})
</script>

<style scoped>
.admin-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>